package com.geese.filter.rsa;

import javax.crypto.Cipher;
import java.security.*;
import java.security.spec.PKCS8EncodedKeySpec;

/**
 * 私钥拥有者操作
 * Created by lingswill on 2016/11/14.
 */
public class RSAForPrivateCodec extends BasicCodec {
    private static final String ALGORITHM = "RSA";

    //rsa，签名算法可以是 md5withrsa 、 sha1withrsa 、 sha256withrsa 、 sha384withrsa 、 sha512withrsa
    private static final String SIGN_ALGORITHM = "MD5withRSA";

    private static final int KEY_SIZE = 1024;

    public RSAForPrivateCodec(String privateKey, String publicKey) throws NoSuchAlgorithmException {
        super();
        super.privateKey = privateKey;
        super.publicKey = publicKey;
    }

    public RSAForPrivateCodec() throws NoSuchAlgorithmException {
        super();
//        initKey();
    }

    /**
     * @description: 初始化私钥和公钥
     * @author lingswill
     * @date 2016/11/14 15:26
     */
    public void initKey() throws NoSuchAlgorithmException {
        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(ALGORITHM);
        keyPairGenerator.initialize(KEY_SIZE);
        KeyPair keyPair = keyPairGenerator.generateKeyPair();
        PrivateKey rsaPrivateKey = keyPair.getPrivate();
        PublicKey rsaPublicKey = keyPair.getPublic();
        super.privateKey = encoder(rsaPrivateKey.getEncoded());
        super.publicKey = encoder(rsaPublicKey.getEncoded());
    }



    @Override
    public byte[] encrypt(byte[] data) throws Exception {
        PrivateKey rsaPrivateKey = getRSAPrivateKey();
        Cipher cipher = Cipher.getInstance(ALGORITHM);
        cipher.init(Cipher.ENCRYPT_MODE, rsaPrivateKey);
        return cipher.doFinal(data);
    }

    @Override
    public byte[] decrypt(byte[] data) throws Exception {
        PrivateKey rsaPrivateKey = getRSAPrivateKey();
        Cipher cipher = Cipher.getInstance(ALGORITHM);
        cipher.init(Cipher.DECRYPT_MODE, rsaPrivateKey);
        return cipher.doFinal(data);
    }

    /**
     * @description: 获取私钥
     * @author lingswill
     * @date 2016/11/14 15:27
     */
    private PrivateKey getRSAPrivateKey() throws Exception {
        PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(decoder(super.privateKey));
        KeyFactory keyFacotry = KeyFactory.getInstance(ALGORITHM);
        return keyFacotry.generatePrivate(pkcs8EncodedKeySpec);
    }

    /**
     * @param data
     * @description: 使用私钥 对数据进行签名
     * @author lingswill
     * @date 2016/11/14 15:26
     */
    public String sign(byte[] data) throws Exception {
        PrivateKey rsaPrivateKey = getRSAPrivateKey();
        Signature signature = Signature.getInstance(SIGN_ALGORITHM);
        signature.initSign(rsaPrivateKey);
        signature.update(data);
        return encoder(signature.sign());
    }

}
